/ leetcodesolve / Product of Array Except Self - Leetcode 238 - Python.py
swadhinbiswas more problem · 2/6/2025
34f7472
42 lines · 842 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# from typing import List

# class Solution:
#     def productExceptSelf(self, nums: List[int]) -> List[int]:
#         productofall=1
#         for i in range(len(nums)):
#               productofall*=nums[i]
#         for i in range(len(nums)):
#             x=nums[i]
#             if x!=0:
#                 nums[i]=productofall//x
#         return nums
#         #Only For Positive Test Case


from typing import List

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        n=len(nums)
        array=[1]*n
        prefix=1
        for i in range(n):
            array[i]=prefix
            prefix*=nums[i]

        suffix:int=1 

        for i in range(n-2,-1,-1):
            suffix*=nums[i+1]
            array[i]*=suffix 

        return array





print(Solution().productExceptSelf([-1,1,0,-3,3]))